package cn.qqcn.user.controller;

import cn.qqcn.common.vo.Result;
import cn.qqcn.user.entity.User;
import cn.qqcn.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping({"/user"})
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping({"/login"})
    public Result login(User param, @RequestParam("captcha") String captcha, HttpServletRequest request, HttpSession session) {
        if (!CaptchaUtil.ver(captcha, request)) {
            return Result.fail("验证码错误");
        } else {
            User user = this.userService.login(param);
            if (user != null) {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                boolean matches = passwordEncoder.matches(param.getPassword(), user.getPassword());
                if (matches) {
                    user.setPassword((String)null);
                    session.setAttribute("userInfo", user);
                    return Result.success();
                }
            }

            return Result.fail("用户名错误或密码错误");
        }
    }
}
